package com.iqilu.ksd.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.ADActivity;
import com.iqilu.ksd.activity.GalleryActivity;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.LiveListActivity;
import com.iqilu.ksd.activity.MainActivity;
import com.iqilu.ksd.activity.MyActivity;
import com.iqilu.ksd.activity.NewsDetailActivity;
import com.iqilu.ksd.activity.PaikeActivity;
import com.iqilu.ksd.activity.SearchActivity;
import com.iqilu.ksd.adapter.NewsAdapter;
import com.iqilu.ksd.bean.BannerBean;
import com.iqilu.ksd.bean.LiveBarBean;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.CityChangeEvent;
import com.iqilu.ksd.event.FragmentChangeEvent;
import com.iqilu.ksd.utils.ArrayUtils;
import com.iqilu.ksd.utils.BoxUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.view.AutoScrollTextView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 头条新闻
 * Created by Coofee on 2016/10/13.
 */

public class TopFragment extends BaseFragment {

    private static final String TAG = "TopFragment";

    private int page;
    private ArrayList<NewsItemBean> list;
    private ArrayList<BannerBean> bannerList;
    private ArrayList<LiveBarBean> liveBarList;
    private int curLiveBar = 0;
    private LinearLayout layHead;
    private NewsAdapter adapter;
    private RelativeLayout layEmpty;
    private ImageView btReload;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;
    private ImageView btNav;
    private ImageView btBox;
    private AutoScrollTextView marqueeText;
    private RelativeLayout layLivebar;
    private TextView tvTitle;
    private ImageView btChudian;

    private static final int catId = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top, null);
        marqueeText = getView(view, R.id.marqueeText);
        setXHTypeface(marqueeText);
        layHead = getView(view, R.id.lay_head);
        layHead.setAlpha(0);
        layEmpty = getView(view, R.id.lay_empty);
        btReload = getView(view, R.id.bt_reload);
        tvTitle = getView(view, R.id.tv_title);
        tvTitle.setText(getString(R.string.app_name));
        setZHTypeface(tvTitle);
        btChudian = getView(view,R.id.bt_chudian);
        btChudian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BoxUtils.getInstance().init(context).show();
            }
        });
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        rvList.setHasFixedSize(true);
        layLoading = getView(view, R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);
        layLivebar = getView(view, R.id.lay_livebar);
        marqueeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                LiveBarBean item = liveBarList.get(0);
                if (item.getIsgroup() == 1) {
                    intent = new Intent(context, LiveListActivity.class);
                } else {
                    intent = new Intent(context, LiveActivity.class);
                }
                int mId = item.getId();
                int userId = item.getUid();
                String title = item.getTitle();
                String album = item.getLitpic();
                String shareurl = item.getShareurl();
                intent.putExtra("id", mId);
                intent.putExtra("groupid", mId);
                intent.putExtra("userid", userId);
                intent.putExtra("title", title);
                intent.putExtra("album", album);
                intent.putExtra("shareurl", shareurl);
                startActivity(intent);
            }
        });

        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                layLoading.setVisibility(View.VISIBLE);
                xRefreshView.setVisibility(View.VISIBLE);
                getHead();
                getLiveBar();
            }
        });
        adapter = new NewsAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(context));

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getHead();
                getLiveBar();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);
        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private float totalDy = 0;
            private int lastPosition = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                int mPoition = layoutManager.findFirstVisibleItemPosition();
                if (mPoition == 0) {
                    setToolBarAlpha(totalDy);
                }
                if(lastPosition ==1 && mPoition == 0){
                    refreshHandler.sendEmptyMessage(0);
                }
                lastPosition = mPoition;
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
        adapter.setOnItemClickListener(onItemClickListener);
        btNav = getView(view, R.id.bt_nav);
        btNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).openDrawer();
            }
        });
        btBox = getView(view, R.id.bt_box);
        btBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MyActivity.class));
            }
        });
        FileUtils.createOrExistsDir(CacheUtils.getVideoDir(context));
        clearVideoCache();
        page = 1;
        getHead();
        getLiveBar();
        return view;
    }

    private void getLiveBar() {
        String url = Api.URL_LIVE_BAR;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                layLivebar.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                liveBarList = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<LiveBarBean>>() {
                });
                if (liveBarList != null && liveBarList.size() > 0) {
                    initLiveBar();
                    layLivebar.setVisibility(View.VISIBLE);
                } else {
                    layLivebar.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initLiveBar() {
        if (getActivity() == null) return;
        marqueeText.setText("" + liveBarList.get(curLiveBar).getTitle());
        marqueeText.init(getActivity().getWindowManager());
        marqueeText.startScroll();
    }

    private void getHead() {
        String url = Api.URL_SLIDE + "?catid=" + catId;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                bannerList = null;
                list = new ArrayList<NewsItemBean>();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                getList();
            }

            @Override
            public void onResponse(String response, int id) {
                bannerList = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<BannerBean>>() {
                });
                if (bannerList != null && bannerList.size() > 0) {
                    NewsItemBean bean = new NewsItemBean();
                    bean.setBannerList(bannerList);
                    bean.setType(NewsType.HEAD);
                    list.add(bean);
                    List<String> urls = new ArrayList<String>();
                    for (BannerBean item : bannerList) {
                        File file = new File(item.getVideourl());
                        String path = CacheUtils.getVideoDir(context) + file.getName();
                        if (!FileUtils.isFileExists(path)) {
                            urls.add(item.getVideourl());
                        }
                    }
                    downloadVideos(urls);
                }
                getList();
            }
        });
    }

    private void getList() {
        String url = Api.URL_ARTICLE_LIST + "?page=" + page + "&catid=" + catId;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                if (page == 1) {
                    setEmpty();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<NewsItemBean> data = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                if (page == 1) {
                    if (data == null || data.size() == 0) {
                        setEmpty();
                        return;
                    }
                    list.addAll(data);
                    adapter.setData(list);
                } else {
                    data = ArrayUtils.removeSame(list, data);
                    if (data == null || data.size() == 0) {
                        Toast.makeText(context, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list == null) {
                        return;
                    }
                    list.addAll(data);
                    adapter.setData(list);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void setEmpty() {
        adapter.setData(null);
        adapter.notifyDataSetChanged();
        layEmpty.setVisibility(View.VISIBLE);
        xRefreshView.setVisibility(View.GONE);
    }

    private void setToolBarAlpha(float length) {
        float height = ScreenUtils.getScreenHeight(context);
        float mAlpha = length * 2 / height;
        if (mAlpha > 1.0f) {
            mAlpha = 1.0f;
        }
        if (length < height / 10) {
            layHead.setAlpha(0);
        } else {
            layHead.setAlpha(mAlpha);
        }
//        imgLogo.setTop(top);
//        imgLogo.setAlpha(1.0f - (mAlpha * 1.5f));
//        imgLogo.setScaleX(1.0f - mAlpha);
//        imgLogo.setScaleY(1.0f - mAlpha);
    }

    Handler refreshHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(TAG,"handleMessage====");
            adapter.notifyDataSetChanged();
        }
    };

    private NewsAdapter.OnItemClickListener onItemClickListener = new NewsAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            String type;
            Intent intent = null;
            NewsItemBean item = list.get(position);
            if (item.getType().equals(NewsType.HEAD)) {
                type = item.getRealtype();
            } else {
                type = item.getType();
            }
            if (type.equals(NewsType.ARTICLE)) {
                intent = new Intent(context, NewsDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
            } else if (type.equals(NewsType.GALLERY) || type.equals(NewsType.PHOTO)) {
                intent = new Intent(context, GalleryActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
                intent.putExtra("position", 0);
            } else if (type.equals(NewsType.AD) || type.equals(NewsType.URL)) {
                intent = new Intent(context, ADActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("type", type);
                intent.putExtra("adUrl", item.getUrl());
                if (type.equals(NewsType.AD)) {
                    intent.putExtra("shareicon", item.getShareicon());
                } else {
                    intent.putExtra("thumb", item.getThumb());
                }
            } else if (type.equals(NewsType.LIVE)) {
                if (item.getIsgroup() == 1) {
                    intent = new Intent(context, LiveListActivity.class);
                } else {
                    intent = new Intent(context, LiveActivity.class);
                }
                intent.putExtra("title", item.getTitle());
                intent.putExtra("groupid", item.getId());
                intent.putExtra("id", item.getId());
            } else if (type.equals(NewsType.CLUE)) {
                intent = new Intent(context, PaikeActivity.class);
                intent.putExtra("id", item.getId());
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };

    private void downloadVideos(List<String> urls) {
        if (urls.size() == 0) return;
        for (String url : urls) {
            File file = new File(url);
            OkHttpUtils.get().url(url).build().execute(new FileCallBack(CacheUtils.getVideoDir(context), file.getName() + "bak") {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(File response, int id) {
                    String name = response.getName().substring(0, response.getName().length() - 3);
                    File newName = new File(CacheUtils.getVideoDir(context) + name);
                    response.renameTo(newName);
                }
            });
        }
    }

    /**
     * 检查视频文件大小，定期清除
     */
    private void clearVideoCache() {
        long mSize = 0;
        try {
            mSize = FileUtils.getFolderSize(new File(CacheUtils.getVideoDir(context)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mSize > 50 * 1024 * 1024) {  //如果缓存视频大于50M则清除
            FileUtils.deleteFilesInDir(CacheUtils.getVideoDir(context));
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(FragmentChangeEvent event) {
        if (rvList == null) return;
        if (event.getId() == R.id.radio_tv) {
            xRefreshView.setTop(2000);
        } else {
            xRefreshView.setTop(0);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        if (adapter != null && list != null && list.size() > 0) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

}
